package com.qf.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author WzYu
 * @date 2022-7-13 下午 4:33
 * 读写锁   锁的降级
 */
public class CaChe {
    static Map map = new HashMap();
    static ReentrantReadWriteLock rw1 = new ReentrantReadWriteLock();
    static Lock r = rw1.readLock();
    static Lock w = rw1.writeLock();
    public static final Object get(String key) {
        r.lock();
        try {
            return map.get(key);
        } finally {
            r.unlock();
        }
    }
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                put("A", 123);
            }
        }, "t1");
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                put("A", 456);
            }
        }, "t2");
        Thread t3 = new Thread(new Runnable() {
            public void run() {
                put("A", 789);
            }
        }, "t3");
        t1.start();
        t2.start();
        t3.start();
    }
    public static final void put(String key, Object value) {
        w.lock();
        try {
            map.put(key, value);
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            r.lock();
            System.out.println(Thread.currentThread().getName() + " " + map.get("A"));
            w.unlock();
            r.unlock();
        }
    }
    public static final void clear() {
        w.lock();
        try {
            map.clear();
        }
        finally {
            w.unlock();
            r.lock();
            System.out.println(Thread.currentThread().getName() + " " + map.get("A"));
            r.unlock();
        }
    }
//    finally
//    {
//        w.unlock();
//        r.lock();
//        System.out.println(Thread.currentThread().getName() + " " + map.get("A"));
//        r.unlock();
//    }
}